<template>
	<div class="ifttt-cont">
		<!--真值反馈事件-->
		<div class="flex-justify-start mar-btm flex-gap-10">
			<div class="flex-com">
				<span class="label-title">规则名称</span>
				<el-input v-model="ruleForm.name" size="mini" style="width: 150px;"></el-input>
			</div>
			<div class="flex-com">
				<span class="label-title">逻辑关系</span>
				<el-select v-model="ruleForm.value.andOr" size="mini" placeholder="子条件之间的逻辑关系" style="width: 150px;">
					<el-option
						v-for="(item, index) in logicOperators" :key="index"
						:label="item.label" :value="item.value"></el-option>
				</el-select>
			</div>
			<div class="flex-com">
				<span class="label-title">是否生效</span>
				<el-select v-model="ruleForm.value.enable" size="mini" placeholder="是否生效" style="width: 80px;">
					<el-option label="是" :value=true></el-option>
					<el-option label="否" :value=false></el-option>
				</el-select>
			</div>
			<div class="mar-lft">
				<slot name="copyRule"></slot>
			</div>
		</div>
		<el-tabs value="condition">
			<el-tab-pane label="判断条件" name="condition" class="ifttt-tab-container">
				<div v-for="(condition, index) in ruleForm.value.conditions" :key="index" class="mar-btm">
					<div class="font-size-14 font-weight-bold mar-btm">
						<span class="font-gray-10">判断条件{{index + 1}}</span>
						【<span class="font-color-primary font-weight-bold">{{conditionText(condition)}}</span>】
						<span class="el-icon-copy-document cursor-pointer font-hover-primary mar-rgt-10"
						      @click="copyEvent(index, ruleForm.value.conditions)"></span>
						<span class="el-icon-delete cursor-pointer font-hover-danger"
						      @click="deleteEvent(index, ruleForm.value.conditions)"></span>
					</div>
					<IftttFiled :rule-form="condition.value1" @resetOperator="resetOperator(condition)"></IftttFiled>
					<div class="flex-com mar-btm">
						<span class="label-title">运算符</span>
						<el-select
							v-model="condition.operator" size="mini"
							placeholder="关系运算符" class="width-input"
							@change="changePorts($event,condition)">
							<el-option
								v-for="(item, index) in findOperators(condition.value1.type)" :key="index"
								:label="item.label" :value="item.value"></el-option>
						</el-select>
					</div>
					<IftttFiledOption
						v-if="condition.operator"
						:rule-form="condition.value2"
						:value1="condition.value1"></IftttFiledOption>
					<el-divider></el-divider>
				</div>
				<div class="font-color-primary font-size-12 font-weight-bold pad-rgt">
					<div class="display-inline cursor-pointer" @click="addCondition()">
						<i class="iconfont icon-tianjia"></i><span class="mar-lft-5">添加判断条件</span>
					</div>
				</div>
			</el-tab-pane>
			<el-tab-pane label="条件满足时" name="if" class="ifttt-tab-container">
				<ActionComponent :iftttLogic="true" :relAction="ruleForm.value.actions"   @dragEvent="(val) =>dragActions(val,ruleForm)"></ActionComponent>
			</el-tab-pane>
			<el-tab-pane label="条件不满足时" name="else" class="ifttt-tab-container">
				<ActionComponent :iftttLogic="true" :relAction="ruleForm.value.elseActions"   @dragEvent="(val) =>dragElseActions(val,ruleForm)"></ActionComponent>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>
<script>
	import IftttFiled from './IftttFiled.vue'
	import IftttFiledOption from './IftttFiledOption.vue'
  import {confirmHandle, deepCopy, getAtomicAttr} from "@/utils";
	import {operators} from "@/config/common";
  import {mapState} from "vuex";
	export default {
		name: 'IftttState',
		components: {
			IftttFiled, IftttFiledOption,
			ActionComponent: () => import('./ActionComponent.vue'),
		},
		props: {
			ruleForm: {
				type: Object,
				default: () => {
					return {};
				},
			},
			conditions: {
				type: Object,
				default: () => {
					return {};
				},
			},
			ifttt: {
				type: Boolean,
				default: () => {
					return false;
				},
			},
		},
		data() {
			return {
				logicOperators: Object.values(operators.logic),
				deviceOperators: Object.values(operators.rel),
				roomOperators: Object.values(operators.roomRel),
			}
		},
		computed: {
      ...mapState({
	      globalVarList: (state) => state.ide.globalVarList,
      }),
			conditionText() {
				return (condition = {}) => {
					const {value1 = {}, operator = '', value2 = {}} = condition;
          let valuesName=''
          //解译value2
          switch (value2.type) {
            case 'relatedAtomic':
              const componentKey=value2.value.split('.')[0]
              const componentName=value2.value.split('.')[1]
              const widgetValues = getAtomicAttr(componentKey, 'ports');
              const widgetValuesName = widgetValues.find(v => v.key === componentName).name;
              valuesName = `${getAtomicAttr(componentKey, 'name')}的${widgetValuesName}`;
              break;
            case 'relatedGlobal':
              valuesName= this.globalVarList.find(item => item.key === value2.value).name;
              break;
              default:
              valuesName=value2.value
              break;
          }
					return `${value1.name}${operator}${valuesName}`
				}
			}
		},
		methods: {
			//添加判断条件
			addCondition() {
				const conditions = this.ruleForm.value.conditions;
				const lastValue = conditions[conditions.length - 1] ? conditions[conditions.length - 1] : {};
				if (this.ruleForm.value.conditions.length > 0 && (!lastValue.operator || lastValue.value2.value.length === 0) && lastValue.value2.autoType !== 4) {
					this.$notify({
						message: '请填写完整判断条件',
						type: 'warning',
						duration: 3000,
					});
					return false;
				}
				if (this.ifttt) {
					const value1 = deepCopy(this.conditions);
					delete value1.actions;
					this.ruleForm.value.conditions.push({
						value1: value1,
						operator: '',
						value2: {
							name: '',
							key: '',
							type: 'string',
							value: ''
						}
					});
				} else {
					this.ruleForm.value.conditions.push({
						value1: {
							name: '',
							key: '',
							type: '',
							value: ''
						},
						operator: '',
						value2: {
							name: '',
							key: '',
							type: 'string',
							value: ''
						}
					});
				}
			},
			findOperators(type) {
				// return type === 'relatedDeviceStatus' ? this.deviceOperators : this.roomOperators;
        return  this.deviceOperators
      },
			// 删除规则
			deleteEvent(index, ruleForm) {
				confirmHandle({label: `确定要删除吗?`}).then(() => {
					ruleForm.splice(index, 1);
				}).catch(() => {
				});
			},
			// 复制规则
			copyEvent(index, ruleForm) {
				const callback = ruleForm[index];
				if (!callback) return;
				ruleForm.splice(index, 0, deepCopy(callback));
			},
			changePorts(val, conditions) {
				if (['relatedAtomic','relatedGlobal'].includes(conditions.value1.type))  {
					conditions.value2.type = conditions.value1.portsType || 'string';
					conditions.value2.isCondition = true;
				}
			},
			resetOperator(condition) {
				condition.operator = '';
				condition.value2.value = '';
				condition.value2.type = condition.value1.portsType || 'string';
				condition.value2.isCondition = true;
			},
			//提交验证
			verify() {
				const lastValue = this.ruleForm;
				const conditions = lastValue ? lastValue.value.conditions : [];
				const lastConditions = conditions[conditions.length - 1];
				//空值就过滤判断
				if (lastValue !== undefined && lastConditions !== undefined && lastConditions.value2.autoType !== 4 && lastConditions.value2.value.length === 0) {
					//判断条件属性必须
					this.$notify({
						message: '请填写完整的判断条件！',
						type: 'warning',
						duration: 3000,
					});
					return false
				} else if (lastValue !== undefined && lastValue.value.actions.length === 0 && lastValue.value.elseActions.length === 0) {
					//满足和不满足条件必须其中一个
					this.$notify({
						message: '请至少填写一项条件满足或不满足后触发的操作！',
						type: 'warning',
						duration: 3000,
					});
					return false;
				} else {
					return true;
				}
			},
      // 拖拽事件
      dragActions(val, ruleForm) {
        ruleForm.value.actions = val
      },
      dragElseActions(val, ruleForm) {
        ruleForm.value.elseActions=val
      }
		}
	}
</script>
<style lang="less" scoped>
	.ifttt-cont {
		width: 100%;

		.flex-com {
			display: flex;
			align-items: center;
			gap: 10px;
		}

		.label-title {
			min-width: 60px;
			color: @colorGray10;
			font-size: 14px;
			text-align: center;
			flex-shrink: 0;
		}

		.divider {
			height: 10px;
			background: @colorGray90;
		}

		.ifttt-tab-container {
			max-height: 500px;
			padding-bottom: 15px;
			overflow: auto;
		}

		.el-collapse {
			padding: 0 15px !important;
		}

		.width-input {
			width: 350px;

			/deep/ .el-input__inner {
				width: 100%;
			}
		}
	}

	/deep/ .el-dialog__body {
		max-height: 700px;
		overflow: auto;
		padding: 16px 0 !important;
	}
</style>
